
Page({
  //需要在视图上展示的内容
  data: {
    courseList: [],
    currentCourseIndex: 0,  
    currentCourse: {},
    performanceTypes: [
      { label: '考勤', value: 'attendance' },
      { label: '回答问题', value: 'answer' },
      { label: '主动提问', value: 'question' }
    ],
    currentType: 'attendance',
    studentList: [],
    showModal: false,
    currentStudent: {},
    currentScore: '',
    performanceTypeLabel: '',
    quickScores: [1, 2, 3, 5], // 快速打分选项
    searchKeyword: '',
    filteredStudentList: [],
    weekList: [],
    weekRange: [] ,
    currentWeekIndex: 0,
    currentWeek: {},
    
  
  },

  onLoad() {
    // 强制重置为初始空状态
    this.setData({
      attendance: [],
      classes: [],
      course_students: [],
      course_weeks: [],
      courses: [],
      students: [],
      teachers: []
    })
    this.fetchCourseList(),
    this.fetchWeekList(),
    console.log('weekList',this.data.weekList)
    wx.cloud.callFunction({
      name: 'performance', // 对应云函数目录名
      data: { action: 'test' }
    }).then(res => {
      console.log('测试结果:', res.result.data)
    })
  },
  // 添加onShow生命周期函数，确保页面显示时刷新数据
  onShow() {
    // 检查是否已加载课程
    if (this.data.courseList && this.data.courseList.length > 0) {
      const courseId = this.data.currentCourse._id;
      const weekNumber = this.data.currentWeek.weekNumber;
      
      // 重新获取周次列表
      this.fetchWeekList();
      
      // 重新获取学生表现数据
      if (courseId && weekNumber) {
        this.fetchStudentList(courseId, weekNumber, this.data.searchKeyword);
        console.log('[表现记录] 页面显示，刷新学生表现数据');
      }
    } else {
      // 如果没有课程数据，重新加载
      this.fetchCourseList();
    }
  },
  // 获取课程列表
  async fetchCourseList() {
    try {
      wx.showLoading({ title: '加载中...' })
      const app = getApp();
      const db = app.getDB();
      const res = await db.collection('courses')
        .where({
          teacherId: wx.getStorageSync('teacherId')
        })
        .get()
      this.setData({ 
        courseList: res.data,
        currentCourse: res.data[0] || {}
      })
      console.log('xxx',this.data.courseList)
      if (res.data.length > 0) {
        this.fetchStudentList(res.data[0]._id)
      }

      wx.hideLoading()
    } catch (err) {
      console.error('获取课程列表失败：', err)
      wx.hideLoading()
      wx.showToast({ title: '获取课程失败', icon: 'none' })
    }
  },
  //跳转表现记录编辑页面-把数据(学生姓名，id，学号，考勤，回答，提问，总分)一起带过去，不然又要查询。
    // 跳转表现记录编辑页面
    navigateToEdit(e) {
      const student = e.currentTarget.dataset.student;
      // console.log('student:',student._id);
      const { courseList, currentCourseIndex} = this.data;
      // console.log('courses:',courseList[currentCourseIndex]._id)
      const {weekList,currentWeekIndex} = this.data;
      // console.log('SSSSS',weekList[currentWeekIndex].weekNumber);
      wx.navigateTo({
        url: `/pages/performance/editPerformance?courseId=${courseList[currentCourseIndex]._id}&studentId=${student._id}&weekNumber=${weekList[currentWeekIndex].weekNumber}`
      });
    },
  // 获取周次列表
async fetchWeekList() {
  try {
    const app = getApp();
    const db = app.getDB();
    const res = await db.collection('course_weeks').where({
      courseId: this.data.currentCourse._id
    }).get();
    this.setData({
      weekList: res.data,
      currentWeek: res.data[0] || {},
    
    });
    console.log('get:',res.data)

  } catch (err) {
    console.error('获取周次列表失败：', err);
    wx.showToast({ title: '获取周次失败', icon: 'none' });
  }
},

// 处理周次选择
handleWeekChange(e) {
  const index = e.detail.value;
  this.setData({
    currentWeekIndex: index,
    currentWeek: this.data.weekList[index]
  });
},
// 根据课程id和周次获取学生列表（可能会有学生姓名的关键词搜索）
async fetchStudentList(courseId, weekNumber, studentName) {
  // 防止重复请求
  if (this.isLoading) return;
  this.isLoading = true;
  console.log('JIN RU  API----:',courseId);
  try {
    wx.showLoading({ title: '加载学生名单...' });
    
    // 参数验证
    if (!courseId) {
      throw new Error('缺少课程ID参数');
    }
    
    const teacherId = wx.getStorageSync('teacherId');
    if (!teacherId) {
      throw new Error('未找到教师身份信息，请重新登录');
    }
    
    // 获取数据库引用
    const app = getApp();
    const db = app.getDB();
    const _ = db.command;
    
    // 构造查询条件
    
    // 1. 权限验证
    try {
      const course = await db.collection('courses').doc(courseId).get();
      if (!course.data || course.data.teacherId !== teacherId) {
        throw new Error('无权限访问该课程');
      }
    } catch (error) {
      console.error('权限验证失败:', error);
      throw new Error('课程不存在或无权限访问');
    }
    
    // 2. 查询课程学生关系
    const courseStudentsRes = await db.collection('course_students')
      .where({ courseId })
      .limit(100)
      .get();
    
    // 3. 处理学生ID列表
    const studentIds = courseStudentsRes.data.map(x => x.studentId);
    if (studentIds.length === 0) {
      this.setData({ studentList: [] });
      wx.hideLoading();
      return;
    }
    console.log('产讯参数---studentName:', studentName);
    // 4. 构建查询条件
    const filter = { _id: _.in(studentIds) };
    console.log('产讯参数---studentIds:', studentIds);
    // 5. 查询学生数据
    if (studentName && studentName.trim() !== '') {
      // 安全处理正则表达式
      const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      filter.studentName = db.RegExp({
        regexp: `.*${escapeRegExp(studentName.trim())}.*`,
        options: 'i'
      });
    }
    
    // 5. 获取学生数据
    const studentsRes = await db.collection('students')
      .where(filter)
      .field({
        studentName: true,
        studentId: true,
        studentNumber: true, 
        // 其他需要的字段
      })
      .limit(100)
      .get();
    console.log('all ->student --:', studentsRes);

    // 6. 查询表现数据
const performanceRes = await db.collection('performance')
.where({
  courseId,
  weekNumber: Number(weekNumber),
  studentId: _.in(studentsRes.data.map(s => s._id))
})
.field({
  studentId: true,
  attendance: true,
  answer: true,
  question: true
})
.get();
    
   // 7. 使用Map优化查找性能 - 改进处理空记录的方式
const performanceMap = {};
performanceRes.data.forEach(p => {
  performanceMap[p.studentId] = p;
});

// 8. 合并数据 - 确保每个学生都有默认的表现记录
const studentList = studentsRes.data.map(student => {
  // 获取表现记录，如果不存在则创建一个包含默认值的对象
  const performance = performanceMap[student._id] || {
    attendance: 0,
    answer: 0,
    question: 0
  };
  
  // 确保所有表现字段都有值，避免undefined
  const attendance = performance.attendance || 0;
  const answer = performance.answer || 0;
  const question = performance.question || 0;
  
  return {
    ...student,
    attendance,
    answer,
    question,
    total: attendance + answer + question
  };
  
});

// 9. 排序和分页 - 添加排序和分页逻辑
    
    this.setData({ studentList });
    console.log('获取学生列表成功：', studentList);
    
  } catch (err) {
    console.error('获取学生列表失败：', err);
    wx.showToast({ 
      title: err.message || '获取学生名单失败', 
      icon: 'none' 
    });
  } finally {
    wx.hideLoading();
    this.isLoading = false;
  }
},
handleCourseChange(e) {
  const index = e.detail.value
  const courseId = this.data.courseList[index]._id
  this.setData({
    currentCourseIndex: index,
    currentCourse: this.data.courseList[index],
    courseId: courseId
  })
},
   // 显示添加学生弹窗
   showAddStudentModal() {
    this.setData({
      showAddModal: true,
      newStudent: {
        name: '',
        studentId: '',
        attendance: '',
        answer: '',
        question: ''
      }
    })
  },
   // 处理新学生信息输入
   handleNewStudentInput(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`newStudent.${field}`]: e.detail.value
    })
  },

  // 取消添加学生
  cancelAddStudent() {
    this.setData({ showAddModal: false })
  },
  // 显示分数输入弹窗
  showScoreInput(e) {
    const { type, studentId } = e.currentTarget.dataset
    const student = this.data.studentList.find(s => s.id === studentId)
    const typeLabel = this.data.performanceTypes.find(t => t.value === type).label
    this.setData({
      showModal: true,
      currentStudent: student,
      currentScore: student[type] || '',
      currentType: type,
      performanceTypeLabel: typeLabel
    })
  },

  // 处理分数输入
  handleScoreInput(e) {
    this.setData({ currentScore: e.detail.value })
  },

  // 设置快速分数
  setQuickScore(e) {
    const score = parseInt(e.currentTarget.dataset.score)
    this.setData({ currentScore: score })
  },

  // 取消打分
  cancelScore() {
    this.setData({ showModal: false })
  },

  // 确认打分
  confirmScore() {
    const { currentStudent, currentType, currentScore, studentList } = this.data
    const score = parseInt(currentScore) || 0

    // 更新学生列表中的分数
    const updatedList = studentList.map(student => {
      if (student.id === currentStudent.id) {
        const updatedStudent = { ...student, [currentType]: score }
        updatedStudent.total = (updatedStudent.attendance || 0) + 
                             (updatedStudent.answer || 0) + 
                             (updatedStudent.question || 0)
        return updatedStudent
      }
      return student
    })

    this.setData({
      studentList: updatedList,
      showModal: false
    })
  },

  // 获取当前日期
  getCurrentDate() {
    const now = new Date()
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
  },

  // 确认添加学生
  async confirmAddStudent() {
    try {
      const { newStudent, currentCourse } = this.data
      
      // 表单验证
      if (!newStudent.name?.trim()) {
        wx.showToast({ title: '请输入学生姓名', icon: 'none' })
        return
      }
      if (!newStudent.studentId?.trim()) {
        wx.showToast({ title: '请输入学号', icon: 'none' })
        return
      }
      wx.showLoading({ title: '添加中...' })
      const app = getApp();
      const db = app.getDB();
      // 添加学生基本信息
      const studentRes = await db.collection('students').add({
        data: {
          name: newStudent.name,
          studentId: newStudent.studentId,
          courseId: currentCourse._id,
          createTime: db.serverDate()
        }
      })
      // 添加表现记录
      await db.collection('performance').add({
        data: {
          courseId: currentCourse._id,
          courseName: currentCourse.courseName,
          studentId: studentRes._id,
          studentName: newStudent.name,
          date: this.getCurrentDate(),
          attendance: Number(newStudent.attendance) || 0,
          answer: Number(newStudent.answer) || 0,
          question: Number(newStudent.question) || 0,
          total: (Number(newStudent.attendance) || 0) + 
                 (Number(newStudent.answer) || 0) + 
                 (Number(newStudent.question) || 0),
          teacherId: wx.getStorageSync('teacherId'),
          createTime: db.serverDate()
        }
      })
      wx.hideLoading()
      wx.showToast({
        title: '添加成功',
        icon: 'success'
      })

      this.setData({ showAddModal: false })
      // 刷新学生列表
      this.fetchStudentList(currentCourse._id)

    } catch (err) {
      console.error('添加学生失败：', err)
      wx.hideLoading()
      wx.showToast({
        title: '添加失败',
        icon: 'none'
      })
    }
  },
  getSerarchName(e){
    // console.log('getDad:',e.detail.value)
    this.setData({
     searchKeyword:e.detail.value 
    })
    // console.log('getMod:',this.data.searchKeyword)

  },
  // 搜索学生
  triggerSearch() {
    if (!this.data.currentCourse._id) {
      wx.showToast({ title: '请先选择课程', icon: 'none' })
      return
    }
    if (!this.data.currentWeek.weekNumber) {
      wx.showToast({ title: '请先选择周次', icon: 'none' })
      return
    }
    // 添加搜索关键词日志验证
    console.log('当前搜索关键词:', this.data.searchKeyword)
    this.fetchStudentList(
      this.data.currentCourse._id,
      this.data.currentWeek.weekNumber,
      this.data.searchKeyword
    )
    console.log('currentCourse._id:', this.data.currentCourse._id);
    console.log('currentWeek.weekNumber:', this.data.currentWeek.weekNumber);
    console.log('searchKeyword:', this.data.searchKeyword);
  },
  // 保存表现记录
  async savePerformance() {
    try {
      wx.showLoading({ title: '保存中...' })
      const app = getApp();
      const db = app.getDB();
      // 批量保存每个学生的表现记录
      const promises = this.data.studentList.map(student => {
        const performanceData = {
          courseId: this.data.currentCourse._id,
          courseName: this.data.currentCourse.courseName,
          studentId: student.id,
          studentName: student.name,
          date: date,
          attendance: student.attendance || 0,
          answer: student.answer || 0,
          question: student.question || 0,
          total: student.total || 0,
          teacherId: wx.getStorageSync('teacherId'),
          updateTime: db.serverDate()
        }

        return db.collection('performance')
          .where({
            courseId: this.data.currentCourse._id,
            studentId: student.id,
            date: date
          })
          .get()
          .then(res => {
            if (res.data.length > 0) {
              // 更新已有记录
              return db.collection('performance')
                .doc(res.data[0]._id)
                .update({ data: performanceData })
            } else {
              // 创建新记录
              return db.collection('performance')
                .add({ data: performanceData })
            }
          })
      })

      await Promise.all(promises)

      wx.hideLoading()
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      })

    } catch (err) {
      console.error('保存表现记录失败：', err)
      wx.hideLoading()
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      })
    }
  }
})